<template>
  <div class="cont" v-show="contShow">
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="cont_top" label-width="50px">
      <el-form-item style="margin-right: 12px">
        <el-button link type="primary" @click="addbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: rgba(218, 111, 40, 1);
            color: rgba(255, 255, 255, 1);
          ">新增网格员</el-button>
        <el-button link type="primary" @click="alldelbtn" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: rgba(218, 111, 40, 1);
            color: rgba(255, 255, 255, 1);
          ">批量删除</el-button>
      </el-form-item>
      <el-form-item label="姓名" prop="memberName" style="margin-right: 17px">
        <el-input v-model="queryParams.memberName" placeholder="" @keyup.enter="handleQuery" style="width: 200px" />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus" style="margin-right: 17px" label-width="74px">
        <el-select v-model="queryParams.auditStatus" placeholder="" placement="bottom" @change="handleQuery"
          style="width: 200px">
          <el-option v-for="item in optionstate" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-right: 0">
        <el-button @click="handleQuery" class="btn btnsearch">查询</el-button>
        <el-button @click="resetQuery" class="btn btnreset">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="display: flex">
      <!-- 选项卡· -->
      <div class="card_style">
        <div class="tabtop">网格区域</div>
        <el-tree ref="tree" node-key="id" :data="treeData" :props="defaultProps" default-expand-all
          @node-click="handleNodeClick">
          <template #default="{ node }">
            <span class="custom-tree-node">
              <span v-html="node.label.length > 8 ? node.label.slice(0, 8) + '...' : node.label"
                :title="node.label"></span>
            </span>
          </template>
        </el-tree>
      </div>
      <!-- 表格 -->
      <el-table v-loading="loading" element-loading-text="Loading..." :data="list"
        style="margin-bottom: 20px; min-height: 435px" :header-cell-style="{ background: '#F0F0F0' }"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column align="center" label="姓名" prop="memberName" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            <div class="namecont">
              {{ scope.row.memberName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="联系电话" prop="telephone" min-width="180" />
        <el-table-column align="center" label="所属网格" prop="gridBelonged" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <div class="namecont">
              {{ scope.row.gridBelonged }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="角色" prop="role" min-width="120">
          <template #default="{ row }">
            {{ roletypeRelate(row.role) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="人员身份" prop="identity" width="300" show-overflow-tooltip>
          <template #default="scope">
            <div class="label_style">
              <div v-for="(item, index) in scope.row.identity" class="identity_style" :key="index"
                v-html="typeRelate(item)">
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="审核状态" prop="auditStatus" min-width="120">
          <template #default="scope">
            <div :title="stateTypeObj[scope.row.auditStatus]" :style="stateText(scope.row.auditStatus)"
              class="state_style">{{ stateTypeObj[scope.row.auditStatus] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" width="160">
          <template #default="scope">
            <el-button link type="primary" class="btnhover" @click="editbtn(scope.row)"
              style="color: #3c88f0">编辑</el-button>
            <el-button link type="primary" class="btnhover" @click="delbtn(scope.row)"
              style="color: #3c88f0">删除</el-button>
            <el-button v-if="scope.row.auditStatus === 1" link type="primary" class="btnhover"
              @click="statebtn(scope.row)" style="color: #3c88f0">审核</el-button>
            <div v-else style="width: 42px"></div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-pagination style="font-size: 14px" v-model:current-page="queryParams.pageNo" :hide-on-single-page="value"
      v-model:page-size="queryParams.pageSize" :page-sizes="pageSizes" layout="total,sizes,prev, pager, next,jumper"
      :total="total" @size-change="selectchange" @current-change="handleCurrentChange" />
  </div>
  <AddDialog v-show="addShow" :addShow="addShow" @getadd-show="getaddShow" :editData="editData"
    @getedit-data="geteditData" />
  <ExamineDialog v-show="examineShow" :examineShow="examineShow" @getexamine-show="getexamineShow" :editData="editData"
    @getedit-data="geteditData" />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import AddDialog from './components/addDialog.vue'
import ExamineDialog from './components/examineDialog.vue'
import * as getgridApi from '@/api/countryside/gridmanagement/index'
import globalApi from '@/api/spb/global'
const { push } = useRouter() // 路由
const selectList = ref([]) // 表格选中数据
const loading = ref(true) // 列表加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const value = ref(true)
const pageSizes = [10, 20, 50, 100]
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  memberName: '',
  auditStatus: ''
})
let currentNode = {}
const treeData = ref()
const tree = ref()
const stateTypeObj = {
  1: '待审核',
  2: '审核通过',
  3: '审核驳回'
}
const optionstate = [
  {
    value: 1,
    label: '待审核'
  },
  {
    value: 2,
    label: '审核通过'
  },
  {
    value: 3,
    label: '审核驳回'
  }
]
/** 获取角色类型列表 */
const optionrole = ref([])
const getroleTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_role_type'
  }
  globalApi.getDictData(params).then((res) => {
    optionrole.value = res.list
  })
}
// 角色类型字段映射
const roletypeRelate = (item) => {
  let content = ''
  optionrole.value.forEach((t) => {
    if (t.value == item) {
      content = t.label
    }
  })
  return content
}
const queryFormRef = ref() // 搜索的表单
const addShow = ref(false)
const examineShow = ref(false)
const contShow = ref(true)
const gridBelonged = ref('')
const editData = ref({})
const getaddShow = (val) => {
  addShow.value = val
  contShow.value = !val
}
const getexamineShow = (val) => {
  examineShow.value = val
  contShow.value = !val
}
const geteditData = (val) => {
  handleCurrentChange(val)
}

/** 条数变化 */
const selectchange = (e) => {
  queryParams.pageSize = e
  queryParams.pageNo = 1
  getList()
}
/** 页码变化 */
const handleCurrentChange = (e) => {
  queryParams.pageNo = e
  getList()
}

/** 状态背景色 */
const stateText = (item: any) => {
  const colors = ['rgba(247,165,67,0.4)', 'rgba(29,224,159,0.3)', 'rgba(234,44,16,0.3)']
  const colors2 = ['rgba(234,112,16,1)', 'rgba(57,144,115,1)', 'rgba(221,68,22,1)']
  let colorIndex = 0
  switch (item) {
    case optionstate[0].value:
      colorIndex = 0
      break
    case optionstate[1].value:
      colorIndex = 1
      break
    case optionstate[2].value:
      colorIndex = 2
      break
  }
  return {
    backgroundColor: colors[colorIndex],
    color: colors2[colorIndex]
  }
}
const defaultProps = {
  children: 'children',
  label: 'label'
}
//处理树形数据加value和label
function traverse(nodes) {
  nodes.forEach((node) => {
    if (node.id) {
      node.label = node.gridName
      node.value = node.id
    }
    if (node.children && Array.isArray(node.children)) {
      traverse(node.children)
    }
  })
}
// 获取网格管理列表
function getAreaOrganization() {
  treeData.value = []
  getgridApi.getGridList().then((res) => {
    let cloneData = JSON.parse(JSON.stringify(res)) // 对源数据深度克隆
    cloneData = cloneData.filter((father) => {
      // 循环所有项，并添加children属性
      let branchArr = cloneData.filter((child) => father.id == child.parentId) // 返回每一项的子级数组
      branchArr.length > 0 ? (father.children = branchArr) : '' //给父级添加一个children属性，并赋值
      return father.parentId == 0 //返回第一层
    })
    traverse(cloneData)
    if (cloneData.length === 0) {
      treeData.value = res
    } else {
      treeData.value = cloneData
    }
    nextTick(() => {
      tree.value.setCurrentKey(res[0].id)
      handleNodeClick(res[0])
    })
  })
}
// 节点点击
function handleNodeClick(node) {
  currentNode = node
  gridBelonged.value = node.id
  getList()
}

/** 查询任务列表 */
const getList = async () => {
  const params = {
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize,
    memberName: queryParams.memberName,
    telephone: '',
    gridBelonged: gridBelonged.value,
    role: '',
    auditStatus: queryParams.auditStatus
  }
  getgridApi
    .getGridmemberPage(params)
    .then((res) => {
      let data = reactive(res.list)
      data.forEach((item) => {
        item.identity = item.identity.split(',')
      })
      total.value = res.total
      list.value = data
      if (list.value.length === 0) {
        value.value = true
      } else {
        value.value = false
      }
      loading.value = false
    })
    .catch((error) => {
      loading.value = false
    })
}

/** 批量删除 */
const handleSelectionChange = (e) => {
  selectList.value = e
}
const alldelbtn = () => {
  if (selectList.value.length == 0) {
    ElMessage({
      message: '至少选中一条数据！',
      type: 'warning'
    })
    return
  }

  ElMessageBox.confirm('此操作将永久删除选中网格员, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const idList = reactive([])
      selectList.value.forEach((item) => {
        idList.push(item.id)
      })
      getgridApi.deleteGridmemberList(idList).then((res) => {
        if (res === true) {
          ElMessage.success('删除成功！')
          getList()
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

/** 新增 */
const addbtn = () => {
  addShow.value = true
  contShow.value = false
  editData.value = {}
  editData.value.identity = null
  editData.value.dialogtitle = '新增网格员'
  editData.value.pageNo = 1
}

/** 编辑 */
const editbtn = (row: any) => {
  addShow.value = true
  contShow.value = false
  editData.value = row
  editData.value.role = JSON.stringify(row.role)
  editData.value.dialogtitle = '编辑网格员'
  editData.value.pageNo = queryParams.pageNo
}
/** 获取人员身份类型列表 */
const optionidentity = ref([])
const getTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_person_identity'
  }
  globalApi.getDictData(params).then((res) => {
    optionidentity.value = res.list
  })
}
// 人员身份字段映射
const typeRelate = (item) => {
  let content = ''
  optionidentity.value.forEach((t) => {
    if (t.value == item) {
      content = t.label
    }
  })
  return content
}
/** 审核 */
const statebtn = (row: any) => {
  editData.value = row
  editData.value.pageNo = queryParams.pageNo
  editData.value.result = 'true'
  editData.value.situation = ''
  examineShow.value = true
  contShow.value = false
}

/** 删除 */
const delbtn = (row: any) => {
  ElMessageBox.confirm('此操作将永久删除该网格员, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      getgridApi.deleteGridmember(row.id).then((res) => {
        if (res === true) {
          ElMessage.success('删除成功！')
          getList()
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

/** 查询按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 初始化 **/
onMounted(() => {
  // getList()
  getTypeData()
  getroleTypeData()
  getAreaOrganization()
})
</script>

<style scoped>
.cont {
  background-color: rgba(255, 255, 255, 1);
  color: rgba(16, 16, 16, 1);
  font-size: 14px;
  text-align: center;
  min-height: 557px;
  position: relative;
}

.cont_top {
  text-align: left;
  margin: 4px 0;
}

::v-deep .el-table .cell {
  display: flex;
  justify-content: center;
}

::v-deep .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px #cc352f;
}

::v-deep .el-select__wrapper.is-focused {
  box-shadow: 0 0 0 1px #cc352f;
}

.card_style {
  width: 266px;
  margin-right: 18px;
  height: 500px;
  border: 1px solid rgba(228, 228, 228, 1);
  margin-bottom: 20px;
}

.btn {
  width: 80px;
  height: 30px;
  line-height: 20px;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}

.btnreset {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(187, 187, 187, 1);
  color: rgba(142, 142, 142, 1);
}

.btnsearch {
  background-color: #cc352f;
  color: rgba(255, 255, 255, 1);
  border: 1px solid #cc352f;
}

.btn:hover {
  opacity: 0.8;
}

.btnhover:hover {
  opacity: 0.8;
}

.el-pagination {
  justify-content: center;
}

.namecont {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}

::v-deep .el-form-item__label {
  padding: 0 17px 0 0;
}

.tabtop {
  width: 100%;
  height: 39px;
  border-bottom: 1px solid rgba(228, 228, 228, 1);
  text-indent: 12px;
  text-align: left;
  line-height: 39px;
  font-weight: 550;
}

.state_style {
  width: 70px;
  height: 22px;
  line-height: 22px;
  text-align: center;
  border-radius: 25px;
  padding: 0 5px;
  font-size: 12px;
  border: none;
  cursor: pointer;
  user-select: none;
}

.state_style:hover {
  opacity: 0.8;
}

.identity_style {
  min-width: 87px;
  height: 22px;
  line-height: 20px;
  text-align: center;
  border-radius: 5px;
  padding: 0 5px;
  margin: 0 2px;
  font-size: 12px;
  border: none;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  user-select: none;
  border: 1px solid rgba(16, 90, 215, 1);
  color: #437bc7;
  background: #f1f8ff;
}

.identity_style:hover {
  opacity: 0.8;
}

::v-deep .el-tree-node__content {
  height: 36px;
}

::v-deep .is-current {
  border-right: 3px solid #cc352f;
  color: #cc352f;
}

.label_style {
  display: flex;
  overflow-x: scroll;
  overflow-y: hidden;
  padding: 9px 0 6px 0;
}

::v-deep .label_style::-webkit-scrollbar {
  height: 3px;
}

::v-deep .label_style:hover::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
}

::v-deep .label_style::-webkit-scrollbar-thumb {
  border-radius: 20px;
  background: transparent;
}

::v-deep .label_style::-webkit-scrollbar-track {
  display: none;
}
</style>